﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading;
using System.Threading.Tasks;

namespace AddAsyncInThreadPool
{

    class Program
    {
        //=========================================================================
        //                            说      明
        // 本项目主要介绍向线程池中添加方法，排队示例

        static void Main(string[] args)
        {
            const int x = 1;
            const int y = 2;
            const string lambdaState = "lambda state 2";

            // 1.这里在QueueUserWorkItem的委托中没有传入参数
            ThreadPool.QueueUserWorkItem(AsyncOperation);
            Thread.Sleep(TimeSpan.FromSeconds(2));

            // 2.这里在QueueUserWorkItem的委托中 传入参数"Async state"
            ThreadPool.QueueUserWorkItem(AsyncOperation,"Async state");
            Thread.Sleep(TimeSpan.FromSeconds(2));

            // 3.这里在QueueUserWorkItem的委托中 传入参数"Async state"
            ThreadPool.QueueUserWorkItem(state=> {
                Console.WriteLine($"操作的State:{state}");
                Console.WriteLine($"工作的线程Id:{Thread.CurrentThread.ManagedThreadId}");
                Thread.Sleep(TimeSpan.FromSeconds(2));
            }, "lambda state");

            ThreadPool.QueueUserWorkItem(_ => {
                Console.WriteLine($"操作的State-nm:{x+y},{lambdaState}");
                Console.WriteLine($"工作的线程Id-nm:{Thread.CurrentThread.ManagedThreadId}");
                Thread.Sleep(TimeSpan.FromSeconds(2));
            }, "lambda state hh");

            Console.ReadKey();

            //=========================================================================
            //                              输出结果如下
            //=========================================================================
            //操作状态: { null}
            //工作的线程Id: 3
            //操作状态: Async state
            //工作的线程Id: 4
            //操作的State: lambda state
            //工作的线程Id: 3
            //操作的State - nm:3,lambda state 2
            //工作的线程Id - nm:5
            // 结论：后面3和4中的lambda表达式传入的参数丝毫没有影响
        }


        static void AsyncOperation(object state)
        {
            Console.WriteLine($"操作状态: {state?? "{null}"}");
            Console.WriteLine($"工作的线程Id:{Thread.CurrentThread.ManagedThreadId}");
            Thread.Sleep(TimeSpan.FromSeconds(2));
        }
    }
}
